package org.example.maven.museumuser.common;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static org.example.maven.museumuser.domain.pojo.StaticVariable.Lock_Order_Key;

@Component
public class SimpleRedisLock {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //锁的id
    private static final String Id_Prefix= UUID.randomUUID().toString().substring(0, 8)+"-";
    //读取lua脚本
    private static final DefaultRedisScript<Long> SCRIPT;
    static {
        SCRIPT=new DefaultRedisScript<>();
        SCRIPT.setLocation(new ClassPathResource("lock.lua"));
        SCRIPT.setResultType(Long.class);
    }



    //尝试获取锁
    public boolean tryLock(String key,long timeout){
        String Id=Id_Prefix+Thread.currentThread().threadId();
        return stringRedisTemplate.opsForValue().setIfAbsent(Lock_Order_Key+key, Id,timeout, TimeUnit.SECONDS);
    }

    //释放锁
    public void releaseLock(String key){
        //执行lua脚本释放锁
        stringRedisTemplate.execute(SCRIPT,
                Collections.singletonList(Lock_Order_Key+key),
                Id_Prefix+Thread.currentThread().threadId());
        /*
        String value =stringRedisTemplate.opsForValue().get(Lock_Order_Key+key);//获取锁的id
        //判断锁的id是否是当前线程的锁
        if(value.equals(Id_Prefix+Thread.currentThread().threadId())){
            stringRedisTemplate.delete(key);
        }*/
    }

}
